package com;

import game.logic.Table.Position;
import game.logic.Table.TableSide;

import java.util.Scanner;

import commands.Command;
import commands.CupCommand;
import commands.NoCommand;
import commands.UserCommand;

/**
 * ReceiveThread
 * 
 * This class runs while comms are expected
 * 
 * It decodes the serial data from the chip and creates a Command object to send
 * over to the GameManager
 * 
 * @author jeff
 *
 */
public class ReceiveThread extends Thread {
	public ReceiveThread() {
		
	}
	/**
	 * run method loop over the input / decode / pass along
	 */
	@Override
	public void run() {
		byte command = 0;
		Scanner sc = new Scanner (System.in);
		while (command != -1) {
			command = sc.nextByte();
			Command c = decode(command);//(byte) (command - (byte) 48));
			System.out.println(c.getType());
		}
	}
	
	/**
	 * Decodes the serial command into an abstract Command object
	 * 
	 * 0-31 = no command
	 * 32-41 = right cup
	 * 42-47 = right user
	 * 48-57 = left cup
	 * 58-63 = left user
	 * @param command - serial command from the chip
	 * @return abstract Command object
	 */
	private Command decode(byte command) {
		System.out.println(command);
		Command ret = null;
		if ((command & BuildFlags.VALID) == 0) {
			ret = new NoCommand();
		} else {
			int sideInt = (command & BuildFlags.RIGHTSIDE) >> 4;
			TableSide side = TableSide.getEnumFromInt(sideInt);
			int data = command & BuildFlags.DATA;
			if (data < 10) {
				Position pos = Position.getEnumFromInt(data);
				ret = new CupCommand(side, pos);
			} else {
				ret = new UserCommand(side);
			}
		}
		
		return ret;
	}
}
